package com.example.alspringaop.demo.action;


import com.example.alspringaop.demo.service.IModifyService;
import com.example.alspringaop.demo.service.IQueryService;
import com.example.alspringaop.spring.framework.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 公布接口url
 * @author Tom
 *
 */
@ALController
@ALRequestMapping("/web")
public class MyAction {

	@ALAutowired
	IQueryService queryService;
	@ALAutowired
	IModifyService modifyService;

	@ALRequestMapping("/query.json")
	public ALModelAndView query(HttpServletRequest request, HttpServletResponse response,
								@ALRequestParam("name") String name){
		String result = queryService.query(name);
		return out(response,result);
	}
	
	@ALRequestMapping("/add*.json")
	public ALModelAndView add(HttpServletRequest request,HttpServletResponse response,
			   @ALRequestParam("name") String name,@ALRequestParam("addr") String addr){
		try {
			String result = modifyService.add(name, addr);
			return out(response,result);
		}catch (Throwable e){
			Map<String,String> model = new HashMap<String,String>();
			model.put("detail",e.getCause().getMessage());
			model.put("stackTrace", Arrays.toString(e.getStackTrace()));
			return new ALModelAndView("500",model);
		}
	}
	
	@ALRequestMapping("/remove.json")
	public ALModelAndView remove(HttpServletRequest request, HttpServletResponse response,
								 @ALRequestParam("id") Integer id){
		String result = modifyService.remove(id);
		return out(response,result);
	}
	
	@ALRequestMapping("/edit.json")
	public ALModelAndView edit(HttpServletRequest request,HttpServletResponse response,
			@ALRequestParam("id") Integer id,
			@ALRequestParam("name") String name){
		String result = modifyService.edit(id,name);
		return out(response,result);
	}
	
	
	
	private ALModelAndView out(HttpServletResponse resp,String str){
		try {
			resp.getWriter().write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
